<?php
namespace addons\wanlshop\library\WanlSdk;

use think\Exception;
use think\Request;
use think\Cache;

class Common
{
	/**
	 * Redis连接
	 */
	public static function redis() 
	{
		if (!extension_loaded('redis')) {
			throw new Exception("服务器不支持Redis，请安装Redis和php redis拓展");
		}
		$config = get_addon_config('wanlshop');
		$redis = new \Redis;
		if ($config['redis']['persistent'] == 'Y') {
		    $redis->pconnect($config['redis']['host'], $config['redis']['port'], $config['redis']['timeout'], 'persistent_id_' . $config['redis']['select']);
		} else {
		    $redis->connect($config['redis']['host'], $config['redis']['port'], $config['redis']['timeout']);
		}
		if ('' != $config['redis']['password']) {
		    $redis->auth($config['redis']['password']);
		}
		if (0 != $config['redis']['select']) {
		    $redis->select($config['redis']['select']);
		}
		return $redis;
	}
	
	/**
	 * 创建Token
	 */
	public static function creatToken($key = 'wanlToken') 
	{
		$code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
		$seKey = "KdHjDfh5";
		$code = md5($seKey . substr(md5($code), 8, 10));
		Cache::set($key, $code, 180);
		return $code;
	}
	
	/**
	 * 验证Token
	 * @param {Object} $token
	 */
	public static function checkToken($token, $key = 'wanlToken') 
	{
		if ($token == Cache::get($key)) {
			Cache::set($key, NULL);
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
